﻿using Microsoft.Extensions.Caching.Memory;
using RankDemo.WebApi.Dtos;

namespace RankDemo.WebApi.Services
{
    public class RankHostedService : IHostedService, IDisposable
    {
        private readonly IRankService _rankService;
        private readonly IMemoryCache _memoryCache;
        private Timer? _timer = null;

        public RankHostedService(
            IRankService rankService,
            IMemoryCache memoryCache)
        {
            _rankService = rankService;
            _memoryCache = memoryCache;
        }

        public Task StartAsync(CancellationToken stoppingToken)
        {
            _timer = new Timer(ReloadLeaderboard, null, TimeSpan.Zero, TimeSpan.FromSeconds(120));
            return Task.CompletedTask;
        }

        private void ReloadLeaderboard(object? state)
        {
            var leaderboards = _rankService.GetAll();
            var leaderboardDtos = leaderboards.Select(item => new LeaderboardDto()
            {
                CustomerId = item.CustomerId,
                Score = item.Score,
                Rank = item.Rank
            }).ToList();

            _memoryCache.Set("leaderboard", leaderboardDtos);
        }

        public Task StopAsync(CancellationToken stoppingToken)
        {
            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }
    }
}
